package com.major.thread;

import java.util.ArrayList;
import java.util.List;

public class ProducerAndConsumer {
    public static void main(String[] args) {
        List list = new ArrayList(10);

        // 生产者
        Thread thread1 = new Thread(new Producer(list));
        // 消费者
        Thread thread2 = new Thread(new Consumer(list));

        thread1.setName("生产者");
        thread2.setName("消费者");

        thread1.start();
        thread2.start();

    }
}

// 生产者
class Producer implements Runnable {
    private List list;

    public Producer(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            // 加锁
            synchronized (list) {
                if (list.size() > 9) {
                    try {
                        // 释放锁
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 可以生产
                Object o = new Object();
                list.add(o);
                System.out.println(Thread.currentThread().getName() + "--->"+o);
                list.notifyAll();
            }
        }
    }
}

// 消费者
class Consumer implements Runnable {
    private List list;

    public Consumer(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (list) {
                if (list.size() == 0) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 可以消费
                Object remove = list.remove(0);
                System.out.println(Thread.currentThread().getName() + "--->" + remove);
                list.notifyAll();
            }
        }
    }
}
